package com.csu.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

/**
 * @项目名称：cloud_market
 * @类名称：JsonUtils
 * @类描述：常用JSON操作接口工具包，抽取是为了让解析代码与实际业务代码低耦合。
 * @创建人：TangC
 * @创建时间：2015-6-18 下午3:27:24
 */
public class JsonUtils
{
    private static Logger LOGGER = Logger.getLogger(JsonUtils.class);

    private JsonUtils()
    {

    }

    /**
     * @description：java对象转换为json字符串
     * @author dongg
     * @date 2014-5-9
     * @param obj
     * @return
     */
    public static String obj2JsonStr(Object obj)
    {
        if (obj instanceof String)
        {
            return obj + "";
        }
        ObjectMapper objectMapper = new ObjectMapper();

        String result = null;

        try
        {
            result = objectMapper.writeValueAsString(obj);
        }
        catch (IOException e)
        {
            LOGGER.error("java对象转json字符串发生异常！", e);
        }
        return result;
    }

    /**
     * @description：json字符串转换为指定类
     * @author dongg
     * @date 2014-11-22
     * @param jsonStr
     *            json字符串
     * @param clazz
     *            class类型
     * @return
     */
    public static <T> T jsonStr2Class(String jsonStr, Class<T> clazz)
    {
        T obj = null;

        ObjectMapper objectMapper = new ObjectMapper();

        try
        {
            obj = objectMapper.readValue(jsonStr, clazz);
        }
        catch (IOException e)
        {
            LOGGER.error("json字符串转java对象发生异常！", e);
        }
        return obj;
    }

    /**
     * @description：json字符串转换为List<Pojo>
     * @author dongg
     * @date 2014-11-22
     * @param jsonStr
     * @return
     */
    public static <T> List<T> jsonStr2List(String jsonStr, Class<T> elementClass)
    {
        List<T> resultList = null;

        ObjectMapper objectMapper = new ObjectMapper();

        CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class,
                elementClass);

        try
        {
            resultList = objectMapper.readValue(jsonStr, collectionType);
        }
        catch (JsonParseException e)
        {
            LOGGER.error("json字符串转List对象发生异常！", e);
        }
        catch (JsonMappingException e)
        {
            LOGGER.error("json字符串转List对象发生异常！", e);
        }
        catch (IOException e)
        {
            LOGGER.error("json字符串转List对象发生异常！", e);
        }
        return resultList;
    }
}
